package com.primb.bench.project.home.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.TextView;

import com.bruce.pickerview.popwindow.DatePickerPopWin;
import com.primb.baselibs.util.DateConvertUtils;
import com.primb.baselibs.util.FormatUtils;
import com.primb.baselibs.view.AutoToolbar;
import com.primb.bench.R;
import com.primb.bench.base.SwipeBaseActivity;
import com.primb.bench.common.constant.AppConstant;
import com.primb.bench.common.override.HttpSubscriber;
import com.primb.bench.project.home.contract.PromiseApplyContract;
import com.primb.bench.project.home.entity.LoanCalculateInfoEntity;
import com.primb.bench.project.home.entity.PromiseApplyEntity;
import com.primb.bench.project.home.presenter.PromiseApplyPresenterImpl;
import com.primb.netlibs.exception.ApiException;
import com.suke.widget.SwitchButton;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.subscriptions.CompositeSubscription;

import static com.orhanobut.logger.Logger.t;

/**
 * Created by Chen on 2017/5/18.
 * 功能描述：
 */

public class PromiseApplyActivity extends SwipeBaseActivity implements PromiseApplyContract.View, SwitchButton.OnCheckedChangeListener {

    @BindView(R.id.title_bar)
    TextView titleBar;
    @BindView(R.id.tv_top)
    TextView tvTop;
    @BindView(R.id.tool_bar)
    AutoToolbar toolBar;
    @BindView(R.id.tv_promise_start_date)
    TextView tvPromiseStartDate;
    @BindView(R.id.tv_promise_end_date)
    TextView tvPromiseEndDate;
    @BindView(R.id.et_promise_deposit_day_now)
    EditText etPromiseDepositDayNow;
    @BindView(R.id.et_promise_deposit_day)
    EditText etPromiseDepositDay;
    @BindView(R.id.et_promise_deposit_sum_now)
    EditText etPromiseDepositSumNow;
    @BindView(R.id.et_promise_deposit_sum)
    EditText etPromiseDepositSum;
    @BindView(R.id.switch_promise_basic_account)
    SwitchButton switchPromiseBasicAccount;
    @BindView(R.id.switch_promise_settle_account)
    SwitchButton switchPromiseSettleAccount;
    @BindView(R.id.switch_promise_salary_account)
    SwitchButton switchPromiseSalaryAccount;
    @BindView(R.id.et_promise_other_scene)
    EditText etPromiseOtherScene;
    @BindView(R.id.et_promise_other_scene_detail)
    EditText etPromiseOtherSceneDetail;
    @BindView(R.id.et_promise_remark)
    EditText etPromiseRemark;
    @BindView(R.id.layout_promise_result)
    LinearLayout layoutPromiseResult;
    @BindView(R.id.btn_promise_calculate)
    Button btnPromiseCalculate;
    @BindView(R.id.btn_promise_reset)
    Button btnPromiseReset;
    @BindView(R.id.scroll_promise_apply)
    ScrollView scrollPromiseApply;
    @BindView(R.id.tv_promise_favorable_rate)
    TextView tvPromiseFavorableRate;
    @BindView(R.id.tv_promise_point)
    TextView tvPromisePoint;
    private PromiseApplyPresenterImpl mPresenter;
    public static final int BUTTON_CALCULATE = 0;
    public static final int BUTTON_SAVE = 1;
    private PromiseApplyEntity entity;
    private LoanCalculateInfoEntity info;

    @Override
    protected void onBaseIntent() {
        super.onBaseIntent();
        Intent intent = getIntent();
        info = intent.getParcelableExtra("info");
    }

    @Override
    protected int onBaseLayoutId(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_promise_apply;
    }

    @Override
    protected void onBaseBindView() {
        titleBar.setText("承诺申请");
        toolBar.setNavigationOnClickListener(v -> PromiseApplyActivity.this.finish());
        btnPromiseCalculate.setTag(BUTTON_CALCULATE);
        //防止输入框获取焦点导致scrollview滑动
        scrollPromiseApply.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        scrollPromiseApply.setFocusable(true);
        scrollPromiseApply.setFocusableInTouchMode(true);
        scrollPromiseApply.setOnTouchListener((v, event) -> {
            v.requestFocusFromTouch();
            return false;
        });
        etPromiseDepositSumNow.setEnabled(false);
        etPromiseDepositDayNow.setEnabled(false);
//        etPromiseOtherScene.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                try {
//                    Double aDouble = Double.valueOf(s.toString());
//                    if (aDouble > 100) {
//                        showError("请输入小于100的数值");
//                    }
//                } catch (Exception e) {
//                    showError("请输入正确格式");
//                }
//            }
//        });
    }

    @Override
    protected void onLoadData() {
        entity = info.getPromiseApplyEntity();
        mPresenter = new PromiseApplyPresenterImpl(this, this, info);
        mPresenter.start();
        mPresenter.getPromiseInfo(info.getClientInfoEntity().getCustomerNum());
    }

    @Override
    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
        switch (view.getId()) {
            case R.id.switch_promise_basic_account:
                entity.setPromiseBasicAccount(isChecked);
                break;
            case R.id.switch_promise_settle_account:
                entity.setPromiseSettleAccount(isChecked);
                break;
            case R.id.switch_promise_salary_account:
                entity.setPromiseSalaryAccount(isChecked);
                break;
        }
    }

    @Override
    public void showError(String msg) {
        showToast(msg);
    }

    @Override
    public void showInfo(String avg, String bal) {
        scrollPromiseApply.setVisibility(View.VISIBLE);
        etPromiseDepositSumNow.setText(bal);
        etPromiseDepositDayNow.setText(avg);
    }

    @Override
    public void hideInfo() {
        scrollPromiseApply.setVisibility(View.GONE);
    }

    @Override
    public void showLoading() {
        showLoadingDialog("测算中");
    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }

    @Override
    public void showDatePicker(int code) {
        DatePickerPopWin pickerPopWin = new DatePickerPopWin.Builder(PromiseApplyActivity.this, new DatePickerPopWin.OnDatePickedListener() {
            @Override
            public void onDatePickCompleted(int year, int month, int day, String dateDesc) {
                int yearMonth = DateConvertUtils.getDaysByYearMonth(year, month);
                dateDesc = year + "-" + (month >= 10 ? month : "0" + month) + "-" + yearMonth;
                if (code == 0) {
                    tvPromiseStartDate.setText(dateDesc);
                    entity.setPromiseStartDate(dateDesc);
                } else if (code == 1) {
                    try {
                        String promiseStartDate = entity.getPromiseStartDate();
                        if (promiseStartDate == null || promiseStartDate.equals("")) {
                            showError("请先选择起始日");
                            return;
                        }
                        int monthSpace = DateConvertUtils.getMonthSpace(promiseStartDate, dateDesc);
                        if (monthSpace >= 1) {
                            tvPromiseEndDate.setText(dateDesc);
                            entity.setPromiseEndDate(dateDesc);
                        } else {
                            showError("起始日和兑现日时间差应大于1个月");
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).textConfirm("确认") //text of confirm button
                .textCancel("取消") //text of cancel button
                .btnTextSize(16) // button text size
                .viewTextSize(18) // pick view text size
                .colorCancel(Color.parseColor("#999999")) //color of cancel button
                .colorConfirm(ContextCompat.getColor(this, R.color.colorPrimaryDark))//color of confirm button
                .minYear(1990) //min year in loop
                .maxYear(2550) // max year in loop
                .showDayMonthYear(false) // shows like dd mm yyyy (default is false)
                .dateChose(FormatUtils.DATE_FORMAT.format(new Date())) // date chose when init popwindow
                .build();
        pickerPopWin.dayLoopView.setVisibility(View.GONE);
        pickerPopWin.showPopWin(this);
    }

    @Override
    public void showCalculateResult(PromiseApplyEntity entity) {
        layoutPromiseResult.setVisibility(View.VISIBLE);
        btnPromiseCalculate.setText("保    存");
        btnPromiseCalculate.setTag(BUTTON_SAVE);
//        mHandler.post(() -> {
//            int top = layoutPromiseResult.getTop();
//            scrollPromiseApply.moothScrollTo(0, top);
//        });
        tvPromiseFavorableRate.setText(FormatUtils.format(Double.valueOf(entity.getPromiseFavorableRate()) * 100));
        tvPromisePoint.setText(entity.getPromisePoint());
    }


    @Override
    public void setResultToCalculate() {
        Intent intent = new Intent();
        intent.putExtra("info", entity);
        setResult(AppConstant.LOAN_PROMISE_RESULT, intent);
        this.finish();
    }

    @Override
    public void resetView() {
        layoutPromiseResult.setVisibility(View.GONE);
        btnPromiseCalculate.setVisibility(View.VISIBLE);
        tvPromiseStartDate.setText("yyyy-MM-dd");
        tvPromiseEndDate.setText("yyyy-MM-dd");
        etPromiseOtherScene.setText("");
        etPromiseDepositDay.setText("");
        etPromiseDepositDayNow.setText("");
        etPromiseDepositSum.setText("");
        etPromiseDepositSumNow.setText("");
        etPromiseOtherSceneDetail.setText("");
        etPromiseRemark.setText("");
        switchPromiseSettleAccount.setChecked(false);
        switchPromiseSalaryAccount.setChecked(false);
        switchPromiseBasicAccount.setChecked(false);
        getEntity();
        entity.setPromiseStartDate("");
        entity.setPromiseEndDate("");
        mPresenter.getPromiseInfo(info.getClientInfoEntity().getCustomerNum());
    }

    @Override
    public PromiseApplyEntity getEntity() {
        entity.setPromiseBasicAccount(switchPromiseBasicAccount.isChecked());
        entity.setPromiseSalaryAccount(switchPromiseSalaryAccount.isChecked());
        entity.setPromiseSettleAccount(switchPromiseSettleAccount.isChecked());
        if (!tvPromiseStartDate.getText().toString().equals("yyyy-MM-dd")) {
            entity.setPromiseStartDate(tvPromiseStartDate.getText().toString());
        }
        if (!tvPromiseEndDate.getText().toString().equals("yyyy-MM-dd")) {
            entity.setPromiseEndDate(tvPromiseEndDate.getText().toString());
        }
        entity.setPromiseDepositDayNow(etPromiseDepositDayNow.getText().toString());
        entity.setPromiseDepositDay(etPromiseDepositDay.getText().toString());
        entity.setPromiseDepositSumNow(etPromiseDepositSumNow.getText().toString());
        entity.setPromiseDepositSum(etPromiseDepositSum.getText().toString());
        entity.setPromiseOtherScene(etPromiseOtherScene.getText().toString());
        entity.setPromiseOtherSceneDetail(etPromiseOtherSceneDetail.getText().toString());
        entity.setPromiseRemark(etPromiseRemark.getText().toString());
        return entity;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onRecycle();
    }

    @OnClick({R.id.btn_promise_reset, R.id.btn_promise_calculate, R.id.tv_promise_start_date, R.id.tv_promise_end_date})
    public void onViewClicked(View view) {
        mPresenter.onViewClick(view);
    }

}
